package com.michaelbulava.TFS.ui.helpers;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.ui.DialogWrapper;

import java.awt.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mbulava on 5/6/2015.
 */
public class UIHelpers {

    public static int openOnUIThread(final DialogWrapper dialog){
        final AtomicInteger dialogStatus = new AtomicInteger();
        runOnUIThread(false, new Runnable() {
            @Override
            public void run() {
                dialog.show();
                dialogStatus.set(dialog.getExitCode());
            }
        });
        return dialogStatus.get();
    }

    public static void runOnUIThread(boolean async, Runnable runnable){
        if (!async)
            ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.defaultModalityState());
        else
            ApplicationManager.getApplication().invokeLater(runnable);
    }

    public static void enableComponents(Container containerControl, boolean enable){
        Component[] components = containerControl.getComponents();
        for (Component component : components) {
            component.setEnabled(enable);
            if (component instanceof Container) {
                enableComponents((Container)component, enable);
            }
        }
    }

    public static boolean isOnDispatchThread(){
        return ApplicationManager.getApplication().isDispatchThread();
    }
}
